<template>
  <component :is="props.conf.tag" v-bind="cloneConf" v-model="valueVal">
    <template #default v-for="(itm, index) in form.componentChild[props.conf?.tag]">
      <Childer v-if="props.conf[index]" :tag="props.conf.tag" :conf="props.conf" :child-key="index" />
    </template>
  </component>
</template>

<script setup>
import { defineComponent, defineProps, h, ref, watch, watchEffect } from "vue";
import MobileLayerAutoForm from "./mobileLayerAutoForm";

const props = defineProps({
  conf: {
    type: Object,
    required: true,
  },
  formData: {
    type: Object,
  },
});

const form = new MobileLayerAutoForm();
const valueVal = ref(props.conf.defaultValue);
const cloneConf = ref(props.conf);
const formData = ref(props.formData);

watch(
  props.conf,
  (newValue, oldValue) => {
    cloneConf.value = { ...props.conf };
    valueVal.value = props.conf.defaultValue;
    formData.value = props.formData;

    // checkbox 中tag 不能替换为此处tag的含义
    delete cloneConf.value.tag;
    delete cloneConf.value.defaultValue;
  },
  { deep: true, immediate: true }
);

watch(valueVal, (newValue, oldValue) => {
  props.conf.defaultValue = newValue;
  formData.value[props.conf.vModel] = newValue;
});

const Childer = defineComponent({
  props: {
    tag: {
      type: String,
      required: true,
    },
    childKey: {
      type: String,
      required: true,
    },
    conf: {
      type: Object,
      required: true,
    },
  },
  setup(props, { attrs }) {
    return () => h("div", null, [form.componentChild[props.tag][props.childKey]?.(h, props.conf, props.childKey)]);
  },
});
</script>

<style lang="scss" scoped></style>
